package com.etc.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class DownloadImgController {

    /**
     * 文件下载实现
     * @param filename 传递过来的文件名
      * @param request  请求
     * @param response 响应对象
     * @throws IOException
     */
    @GetMapping("download")
    public void download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
            //如果是当前项目部署路径(是部署路径) =>物理位置+当前文件真实名字
            File file = new File(request.getRealPath("/images/")+filename);

            //设置文件名
            response.setHeader("Content-Disposition","attachment;fileName="+filename);
            //流传递 先输入-再输出
             FileInputStream inputStream = new FileInputStream(file);
             //读取数据
             byte[] bytes = new byte[inputStream.available()];
             inputStream.read(bytes);
             //写入
             OutputStream outputStream = response.getOutputStream();

             outputStream.write(bytes);
             //释放资源
            inputStream.close();
            outputStream.close();
    }

}
